package net.doglog;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.oreilly.servlet.multipart.*;

@SuppressWarnings("serial")
public class FileAdmin extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getRequestDispatcher("/admin/file.jsp").forward(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		MultipartParser mp = new MultipartParser(req, req.getContentLength() * 2);
		mp.setEncoding("UTF-8");
		
		Part rp = null;
		while ((rp = mp.readNextPart()) != null)
			if (rp.isFile() && rp.getName().equals("thefile")) break;
		
		String msg = "Invalid submit.";
		
		if (rp != null) {
			FilePart fp = (FilePart) rp;
			if (fp.getFileName() == null) {
				msg = "You must select a file to upload.";
			} else {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				fp.writeTo(baos);
				
				File file = new File();
				file.setName(fp.getFileName());
				file.setContentType(fp.getContentType());
				file.setContent(baos.toByteArray());
				
				if (file.save()) {
					msg = "File uploaded successfully.";
				} else {
					msg = "Failed to upload.";
				}
			}
		}
		
		req.setAttribute("msg", msg);
		req.getRequestDispatcher("/admin/file.jsp").forward(req, resp);
	}
}
